package scau.gsmg.misp.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import scau.gsmg.misp.dao.BaseDAO;
import scau.gsmg.misp.dao.ICheckoutDAO;
import scau.gsmg.misp.vo.Goods;
import scau.gsmg.misp.vo.Member;
import scau.gsmg.misp.vo.Payment;
import scau.gsmg.misp.vo.SaleOrder;
import scau.gsmg.misp.vo.SaleOrderItems;
import scau.gsmg.misp.vo.User;

/**
 * @Title 收银的所有操作
 * @Group gaoshenmegui
 * @author ZCL
 * @date 2015年4月9日
 */
@Repository
public class CheckoutDAO extends BaseDAO implements ICheckoutDAO {

	private static final Logger logger = Logger.getLogger(CheckoutDAO.class);

	/**
	 * 收银员通过商品条码搜索商品
	 */
	@Override
	public List searchGoodsById(String barcode) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Goods g where g.barcode=?";
		List dataList = new ArrayList();
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, barcode);
			List<Goods> good = query.list();

			for (Goods g : good) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", g.getId());
				jsonMap.put("barcode", g.getBarcode());
				jsonMap.put("name", g.getName());
				jsonMap.put("price", g.getPrice());
				jsonMap.put("unit", g.getUnit());
				jsonMap.put("description", g.getDescription());
				jsonMap.put("amount", 1);
				jsonMap.put("totalprice", g.getPrice() * 1);

				dataList.add(jsonMap);
			}
			if (good.size() > 0) {
				return dataList;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 得到销售单表中最后一条记录
	 */
	@Override
	public String lastSaleRecord() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		// 查询最后一条记录
		String hql = "from SaleOrder s where s.saleOrderId=(select max(s.saleOrderId) from SaleOrder s)";
		try {
			Query query = session.createQuery(hql);
			List<SaleOrder> item = query.list();
			String strOrder = null;
			if (item.size() > 0) {
				SaleOrder order = (SaleOrder) item.get(0);
				strOrder = order.getSaleOrderId();
			}
			if (strOrder == null) {
				return null;
			} else {
				return strOrder;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 得到支付单表中最后一条记录
	 */
	@Override
	public String lastPaymentRecord() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		// 查询最后一条记录
		String hql = "from Payment p where p.paymentId=(select max(p.paymentId) from Payment p)";
		try {
			Query query = session.createQuery(hql);
			List<Payment> item = query.list();
			String strOrder = null;
			if (item.size() > 0) {
				Payment order = (Payment) item.get(0);
				strOrder = order.getPaymentId();
			}
			if (strOrder == null) {
				return null;
			} else {
				return strOrder;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 提取单据
	 */
	@Override
	public List gainSuspend() throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		List dataList = new ArrayList();
		String hql = "from SaleOrder s where s.state=2";
		try {
			Query query = session.createQuery(hql);
			List<SaleOrder> item = query.list();
			for (SaleOrder s : item) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				String customerId = null;
				String customerName = null;
				String cellphone = null;
				String integral = null;
				String discount = null;
				if (s.getMember() != null) {
					customerId = s.getMember().getId().toString();
					cellphone = s.getMember().getCellphone();
					customerName = s.getMember().getName();
					integral = s.getMember().getIntegral().toString();
					discount = s.getMember().getDiscount().toString();
				}
				jsonMap.put("suspendId", s.getId());
				jsonMap.put("date", s.getCreateTime());
				jsonMap.put("id", customerId);
				jsonMap.put("name", customerName);
				jsonMap.put("integral", integral);
				jsonMap.put("discount", discount);
				jsonMap.put("cellphone", cellphone);
				dataList.add(jsonMap);
				logger.info(dataList);
			}
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 获取单据中的商品
	 */
	@Override
	public List gainSuspendGoods(int suspendId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from SaleOrderItems s where s.saleOrder.id=?";
		List dataList = new ArrayList();
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, suspendId);
			List<SaleOrderItems> goods = query.list();
			for (SaleOrderItems s : goods) {
				HashMap<String, Object> jsonMap = new HashMap<String, Object>();
				jsonMap.put("id", s.getGoods().getId());
				jsonMap.put("barcode", s.getGoods().getBarcode());
				jsonMap.put("name", s.getGoods().getName());
				jsonMap.put("price", s.getGoods().getPrice());
				jsonMap.put("unit", s.getGoods().getUnit());
				jsonMap.put("description", s.getGoods().getDescription());
				jsonMap.put("amount", s.getQuantity());
				jsonMap.put("totalprice", s.getPrice());
				dataList.add(jsonMap);
			}
			logger.info("得到的全部商品：" + dataList);
			return dataList;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 删除挂账记录
	 */
	@Override
	public boolean deleteRecord(int suspendId) throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		String hql = "delete SaleOrder s where s.id=?";
		Session session = getSession();
		try {
			Query query = session.createQuery(hql);
			query.setParameter(0, suspendId);
			query.executeUpdate();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 结算——通过收银员id返回收银员
	 */
	@Override
	public User gainCashier(int cashierId) throws Exception {
		Session session = getSession();
		try {
			String hql = "from User u where u.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, cashierId);
			List list = query.list();
			User cashier = new User();
			if (list.size() > 0) {
				cashier = (User) list.get(0);
			} else {
				cashier = null;
			}
			return cashier;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 结算——通过会员id返回会员
	 */
	@Override
	public Member gainCustomer(int customerId) throws Exception {
		Session session = getSession();
		try {
			String hql = "from Member m where m.id=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, customerId);
			List list = query.list();
			Member customer = new Member();
			if (list.size() > 0) {
				customer = (Member) list.get(0);
			} else {
				customer = null;
			}
			return customer;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 更新会员积分
	 */
	@Override
	public boolean updateIntegral(int customerId, double totalPrice)
			throws Exception {
		// TODO Auto-generated method stub
		// 0代表该用户不是会员
		if (customerId != 0) {
			Session session = getSession();
			String hql = "update Member m set m.integral=m.integral+? where m.id=?";
			Query query = session.createQuery(hql);
			int integral = (int) totalPrice;// 消费1元获得1个积分
			query.setParameter(0, integral);
			query.setParameter(1, customerId);
			query.executeUpdate();
			return true;
		}
		return false;
	}

	/**
	 * 销售开单——在销售单生成销售记录
	 */
	@Override
	public SaleOrder createSaleOrder(String saleId, Member customer,
			Double totalPrice, int amount, double receivables) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			Date saleDate = new Date();
			String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(saleDate);
			Timestamp time = Timestamp.valueOf(nowTime);

			SaleOrder saleOrder = new SaleOrder();
			saleOrder.setMember(customer);
			saleOrder.setSaleOrderId(saleId);
			saleOrder.setCreateTime(time);
			saleOrder.setState("0");
			saleOrder.setTotalPrice(totalPrice);
			saleOrder.setAmount(amount);
			saleOrder.setReceivable(receivables);

			Transaction tx = session.beginTransaction();
			session.save(saleOrder);
			tx.commit();
			return saleOrder;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 销售开单——把客户购买的商品信息写入商品销售表
	 */
	@Override
	public boolean writeGoodsItem(String rowObj, SaleOrder saleOrder)
			throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			JSONArray jsonArray = JSONArray.fromObject(rowObj);// 把从前台得到的json字符串转换成json数组
			// 将每一条商品记录保存到数据库
			for (int i = 0; i < jsonArray.size(); i++) {
				String hql = "from Goods g where g.id=?";
				Query query = session.createQuery(hql);
				query.setParameter(0, jsonArray.getJSONObject(i).getInt("id"));
				List goodList = query.list();
				Goods good = (Goods) goodList.get(0);

				int quantity = jsonArray.getJSONObject(i).getInt("amount");// 得到数量
				double price = jsonArray.getJSONObject(i).getDouble(
						"totalprice");// 得到数量
				SaleOrderItems saleOrderItems = new SaleOrderItems(saleOrder,
						good, quantity, price);
				Transaction tx = session.beginTransaction();

				session.save(saleOrderItems);
				tx.commit();
			}
			flag = true;

		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 结算——通过销售单号返回销售单对象
	 */
	@Override
	public SaleOrder gainSaleOrder(String saleId) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		try {
			String hql = "from SaleOrder s where s.saleOrderId=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, saleId);
			List list = query.list();
			SaleOrder saleOrder = new SaleOrder();
			if (list.size() > 0) {
				saleOrder = (SaleOrder) list.get(0);
			} else {
				saleOrder = null;
			}
			return saleOrder;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return null;
	}

	/**
	 * 结算
	 */
	@Override
	public boolean checkout(SaleOrder saleOrder, User cashier,
			String paymentId, Double totalPrice, Double realPay, Double change,
			String paymentMethod) throws Exception {
		// TODO Auto-generated method stub
		boolean flag = false;
		Session session = getSession();
		try {
			Date payDate = new Date();
			String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.format(payDate);
			Timestamp time = Timestamp.valueOf(nowTime);

			Payment payment = new Payment();
			payment.setChanges(change);
			payment.setCreateTime(time);
			payment.setPaymentId(paymentId);
			payment.setPaymentMethod(paymentMethod);
			payment.setRealPay(realPay);
			payment.setSaleOrder(saleOrder);
			payment.setUser(cashier);

			Transaction tx = session.beginTransaction();
			session.save(payment);
			tx.commit();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 结算——把销售单标记为“已支付”或“挂账”，0代表未支付，1代表已支付，2代表挂账
	 */
	@Override
	public boolean updateState(String state, String saleOrderId)
			throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		boolean flag = false;
		try {
			String hql = "update SaleOrder s set s.state=? where s.saleOrderId=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, state);
			query.setParameter(1, saleOrderId);
			query.executeUpdate();
			flag = true;

		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

	/**
	 * 修改库存
	 */
	@Override
	public boolean updateInventory(String rowObj) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		JSONArray jsonArray = JSONArray.fromObject(rowObj);// 把从前台得到的json字符串转换成json数组
		boolean flag = false;
		try {
			for (int i = 0; i < jsonArray.size(); i++) {
				String hql = "update Inventory i set i.quantity=i.quantity-? where i.goods.id=?";
				Query query = session.createQuery(hql);
				query.setParameter(0,
						jsonArray.getJSONObject(i).getInt("amount"));
				query.setParameter(1, jsonArray.getJSONObject(i).getInt("id"));
				query.executeUpdate();
				flag = true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e);
		} finally {
			session.close();
		}
		return flag;
	}

}
